package com.zmn.plat.admin.controller.pilot;

import com.google.common.base.Joiner;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.LayuiTableResponseDTO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.plat.admin.controller.PlatBaseController;
import com.zmn.plat.business.interfaces.pilot.ChannelPriceBService;
import com.zmn.plat.business.interfaces.pilot.ChannelPriceCategoryBService;
import com.zmn.plat.common.constant.OnePriceConsts;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.common.util.StringToArrayUtil;
import com.zmn.plat.manager.dictionary.OnePriceDict;
import com.zmn.plat.model.entity.pilot.*;
import com.zmn.plat.services.interfaces.area.BaseAreaService;
import com.zmn.plat.services.interfaces.channel.ChannelService;
import com.zmn.plat.services.interfaces.pilot.ChannelPriceCategoryService;
import com.zmn.plat.services.interfaces.pilot.ChannelPriceLogService;
import com.zmn.plat.services.interfaces.pilot.ChannelPriceService;
import com.zmn.plat.services.interfaces.servcategory.ServCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.directory.api.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 渠道试点基础修改Controller
 *
 * @author guoqiao
 * @since 2021-06-25 10:16:42
 */
@Slf4j
@RestController
@RequestMapping("/pilot/channel/price")
public class ChannelPriceModifyController extends PlatBaseController {

    @Resource
    private ChannelPriceService channelPriceService;

    @Resource
    private ChannelPriceCategoryBService categoryBService;

    @Autowired
    protected ChannelService channelService;

    @Autowired
    protected BaseAreaService baseAreaService;

    @Autowired
    protected ServCategoryService servCategoryService;

    @Autowired
    protected ChannelPriceBService bService;

    @Resource
    ChannelPriceLogService channelPriceLogService;
    @Autowired
    private ChannelPriceCategoryService channelPriceCategoryService;

    /**
     * 描述: 保存
     *
     * @author guoqiao
     * @since 2021-06-25 10:16:42
     */
    @RequestMapping("/addEdit")
    public ResponseDTO addEdit(@RequestBody ChannelPriceVO channelPrice) {

        List<Integer> priceIds = new ArrayList<>();

        try {
            /**
             * 将元转换成分
             */
//            if (!NumberUtil.isNullOrZero(channelPrice.getDeposit())) {
//                channelPrice.setDeposit(channelPrice.getDeposit() * 100);
//            }
//            if (!NumberUtil.isNullOrZero(channelPrice.getDepositDeductionAmount())) {
//                channelPrice.setDepositDeductionAmount(channelPrice.getDepositDeductionAmount() * 100);
//            }

            // 获取登录信息
            LoginStaff mcStaff = getMcStaff();

            if (Strings.isEmpty(channelPrice.getChannelIds())) {
                return ResponseDTO.fail("渠道ID不能为空！");
            }

            // 保存或修改多个渠道试点配置
            List<Integer> channelIdList = StringUtil.convertStrsToList(channelPrice.getChannelIds());
            channelPrice.setStatus(GlobalDict.STATUS_ENABLE);

            channelIdList.forEach(x -> {
                ChannelPriceVO item = new ChannelPriceVO();
                BeanUtils.copyProperties(channelPrice, item);
                item.setChannelId(x);
                priceIds.add(bService.submitOnePrice(item, mcStaff));
            });

            return ResponseDTO.success(Joiner.on(",").join(priceIds));
        } catch (Exception e) {
            log.error("新增/修改失败,Exception{},msg{}", e, e.getMessage());
            return ResponseDTO.fail("操作失败！");
        }
    }

    /**
     * 描述: 修改状态
     *
     * @param ids    id集合
     * @param status 状态
     * @author guoqiao
     * @since 2021-06-25 10:16:42
     */
    @RequestMapping(value = "/updateStatus")
    public ResponseDTO<Boolean> updateStatus(@RequestParam(value = "ids") String ids,
                                             @RequestParam(value = "status") Integer status) {
        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择要更改状态的数据！");
        }

        try {
            List<Integer> list = StringUtil.convertStrsToList(ids);
            LoginStaff mcStaff = getMcStaff();
            // 启动时需要校验是否添加应用分类，未添加这不能启动
//            if (status.equals(GlobalDict.STATUS_ENABLE)) {
//                checkwhetherOrNotItCanStart(list);
//            }
            channelPriceService.updateStatusBatch(list, status, getMcStaffRealName());
            //保存日志
            List<ChannelPriceLog> logList = new ArrayList<>();
            list.forEach(x -> logList.add(new ChannelPriceLog()
                    .setContent(String.format("状态变更为:\"%s\"", OnePriceDict.getStatus(status)))
                    .setAbutmenterType(3)
                    .setRelationId(x)
                    .setCreateTime(DateUtil.getNow())
                    .setAbutmenter(mcStaff.getStaffName())
                    .setAbutmenterId(mcStaff.getStaffId())));
            channelPriceLogService.insertBatch(logList);
            return ResponseDTO.success(true, "操作成功！");

        } catch (Exception e) {
            log.error("{},{}", e.getMessage(), e);
            return ResponseDTO.fail(String.format("修改状态失败：%s", e.getMessage()));
        }
    }

    /**
     * 描述: 删除
     *
     * @param channelPriceId 主键
     * @author guoqiao
     * @since 2021-06-25 10:16:42
     */
    @RequestMapping(value = "/delete")
    public ResponseDTO delete(@RequestParam(value = "channelPriceId") Integer channelPriceId) {

        try {
            if (NumberUtil.isNullOrZero(channelPriceId)) {
                return ResponseDTO.fail("请选择要删除的数据！");
            }
            LoginStaff mcStaff = getMcStaff();
            // 根据ID逻辑修改
            ChannelPrice byKey = channelPriceService.findById(channelPriceId);
            Objects.requireNonNull(byKey);

            ChannelPrice deleteLogic = new ChannelPrice()
                    .setChannelPriceId(channelPriceId)
                    .setStatus(GlobalDict.STATUS_DISABLE)
                    .setDelete(OnePriceConsts.PILOT_LOGICTODELETE_DELETE)
                    .setUpdateTime(DateUtil.getNow());

            channelPriceService.updateByKey(deleteLogic);

            channelPriceCategoryService.deleteByConfigId(channelPriceId, GlobalConsts.NO, GlobalConsts.YES);


            //保存日志
            ChannelPriceLog log = new ChannelPriceLog()
                    .setContent("逻辑删除渠道执行配置")
                    .setAbutmenterType(3)
                    .setRelationId(channelPriceId)
                    .setCreateTime(DateUtil.getNow())
                    .setAbutmenter(mcStaff.getRealName())
                    .setAbutmenterId(mcStaff.getStaffId());

            channelPriceLogService.insert(log);
            return ResponseDTO.success("删除成功！");

        } catch (Exception e) {
            log.error("删除失败,Exception{},msg{}", e, e.getMessage());
            return ResponseDTO.fail("操作失败！");
        }
    }

    /**
     * 保存服务分类
     *
     * @param configId   配置Id
     * @param type       配置类型 1渠道配置 2城市配置
     * @param showType   产品分类 1后台 2前台
     * @param categoryId the category id
     * @return the result dto
     * @author xiangjunming
     * @since 2019/11/21
     */
    @RequestMapping("saveServiceCategory")
    @ResponseBody
    public ResponseDTO saveServiceCategory(String configId, Integer servCategId, Integer type
            , Integer showType, String categoryId) {
        String lable = "保存服务分类";

        try {
            if (StringUtil.isBlank(configId)) {
                return ResponseDTO.fail("配置ID不能为空！");
            }
            List<String> ids = StringUtil.isBlank(categoryId) ? Collections.EMPTY_LIST : Arrays.asList(categoryId.split(GlobalConsts.SPLITER_DEFAULT));

            List<Integer> categoryIds = StringToArrayUtil.convertStrsToList(configId);

            categoryIds.forEach(x -> categoryBService.modifyServiceCategory(x, servCategId, type, showType, ids, getMcStaff().getRealName()));

            return ResponseDTO.success(GlobalConsts.YES, String.format("%s成功！", lable));

        } catch (PlatException e) {
            return ResponseDTO.fail(e.getMessage());
        } catch (Exception e) {
            log.error("error:", e);
            return ResponseDTO.fail(String.format("%s失败！", lable));
        }
    }

    /**
     * 描述: 加载一口价配置操作日志
     *
     * @param channelPriceLogQuery 日志查询对象
     * @return com.zmn.common.dto.LayuiTableResponseDTO
     * @author wangjie
     * @since 10:11 2019/7/8
     **/
    @RequestMapping(value = "loadChannelPriceLog")
    @ResponseBody
    public LayuiTableResponseDTO loadChannelPriceLog(ChannelPriceLogQuery channelPriceLogQuery) {

        ChannelPriceLogQuery query = new ChannelPriceLogQuery();
        query.setRelationId(channelPriceLogQuery.getRelationId());
        Integer count = channelPriceLogService.countByQuery(query);
        query.setTotalCount(count);
        List<ChannelPriceLog> channelPriceLogs = channelPriceLogService.listByQuery(query);

        return LayuiTableResponseDTO.success(query.getTotalCount(), channelPriceLogs);

    }

    /**
     * 判断是否能启动
     *
     * @param list 渠道id
     */
    private void checkwhetherOrNotItCanStart(List<Integer> list) {
        ChannelPriceCategoryQuery categoryQuery = new ChannelPriceCategoryQuery();
        categoryQuery.setConfigIdList(list);
        categoryQuery.setType(OnePriceConsts.CHANNEL_TYPE);
        List<ChannelPriceCategory> categoryList = channelPriceCategoryService.listByQuery(categoryQuery);
        if (CollectionUtils.isEmpty(categoryList)) {
            throw new PlatException(String.format("ID【%s】没有关联应用分类，不能启动！", Joiner.on(",").join(list)));
        }
        // 只要有一条没加应该分类就不能启动
        Map<Integer, List<ChannelPriceCategory>> map = categoryList.stream()
                .collect(Collectors.groupingBy(ChannelPriceCategory::getConfigId));

        List<Integer> configIds = new ArrayList<>();
        for (Integer index : list) {
            if (CollectionUtils.isEmpty(map.get(index))) {
                configIds.add(index);
            }
        }
        if (!CollectionUtils.isEmpty(configIds)) {
            throw new PlatException(String.format("ID【%s】没有关联应用分类，不能启动！", Joiner.on(",").join(configIds)));
        }
    }

}
